var jwtUtil = require("../utils/permission/jwtutil"); // 导入token模块
const db = require("../db/mysql"); // 引入 数据库 配置
const bcrypt = require("bcryptjs"); // 引入 bcryptjs 加密模块

/**
 * 用户登录
 * @param { object } ctx
 * * username 账号
 * * password 密码
 * @param { function } next
 * @returns
 */
const login = async (ctx, next) => {
  // 获取客户端IP地址
  try {
    const { username, password } = ctx.request.body;
    // 1. 查找用户
    const [data] = await db.query(
      "SELECT id, username, password, nick, type, email FROM user WHERE username = ?",
      [username]
    );
    const user = data ? data[0] : false;
    // 2. 用户不存在
    if (!user) {
      ctx.body = {
        code: 400,
        message: "用户名或密码错误",
      };
      return;
    }
    // 3. 校验密码
    const isPasswordCorrect = await bcrypt.compare(password, user.password);
    if (!isPasswordCorrect) {
      ctx.body = {
        code: 400,
        message: "用户名或密码错误",
      };
      return;
    }
    // 4. 生成JWT Token
    const payload = {
      id: user.id,
      username: user.username,
      nick: user.nick,
      type: user.type,
      email: user.email,
    };
    const token = jwtUtil.encrypt(payload);
    // 5. 返回结果
    ctx.body = {
      code: 200,
      message: "登录成功",
      data: {
        token, // 返回生成的token
        user: payload,// 返回用户信息
      },
    };
  } catch (err) {
    ctx.body = {
      code: 500,
      msg: "登录失败",
      data: err,
    };
  }
};
/**
 * 添加用户
 * @param {*} ctx
 * * username 用户名 (必填)
 * * password 密码 (必填)
 * * nick 昵称 (可选)
 * * type 用户类型 (可选，默认1)
 * * email 邮箱 (可选)
 * @param {*} next
 * @returns
 */
const addUser = async (ctx, next) => {
  const userData = ctx.tokenObj;
  try {
    const { username, password, nick, type = 1, email } = ctx.request.body;
    // 权限检查
    if (userData.type < type || type > 98) {
      ctx.status = 403;
      ctx.body = {
        code: 403,
        message: "权限不足",
      };
      return;
    }
    
    // 必填字段检查
    if (!username || !password) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: "用户名和密码不能为空",
      };
      return;
    }
    
    // 检查用户是否存在
    const [user] = await db.query(`SELECT * FROM user WHERE username = ?`, [username]);
    if (user.length > 0) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: "用户已存在",
      };
      return;
    }
    
    // 加密密码
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(password, salt);
    
    // 构建SQL和参数
    let sql = `INSERT INTO user (username, password, type, creationTime`;
    let values = [username, hash, type];
    let placeholders = `?, ?, ?, NOW()`;
    
    // 添加可选字段
    if (nick !== undefined) {
      sql += `, nick`;
      values.push(nick);
      placeholders += `, ?`;
    }
    if (email !== undefined) {
      sql += `, email`;
      values.push(email);
      placeholders += `, ?`;
    }
    
    sql += `) VALUES (${placeholders})`;
    
    // 插入用户
    const result = await db.query(sql, values);
    
    ctx.body = {
      code: 200,
      message: "用户添加成功",
      data: result,
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "服务器错误",
      error
    };
  }
};
/**
 * 修改用户信息
 * @param {*} ctx 
 * @param {*} next 
 * @returns 
 */
const updateUser = async (ctx, next) => {
  const currentUser = ctx.tokenObj; // 当前登录用户信息
  try {
    const { id, username, password, nick, type, email } = ctx.request.body;
    
    // 1. 必填字段检查
    if (!id) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: "用户ID不能为空"
      };
      return;
    }
    
    // 2. 权限检查
    // 2.1 获取目标用户信息
    const [targetUser] = await db.query(
      "SELECT id, username, type FROM user WHERE id = ?", 
      [id]
    );
    
    if (!targetUser || targetUser.length === 0) {
      ctx.status = 404;
      ctx.body = {
        code: 404,
        message: "用户不存在"
      };
      return;
    }
    
    // 2.2 检查修改权限
    // 只能修改自己或比自己权限低的用户
    if (currentUser.id !== id && currentUser.type >= targetUser[0].type) {
      ctx.status = 403;
      ctx.body = {
        code: 403,
        message: "无权修改该用户信息"
      };
      return;
    }
    
    // 2.3 检查是否尝试提升权限到比自己高的级别
    if (type !== undefined && currentUser.type < type) {
      ctx.status = 403;
      ctx.body = {
        code: 403,
        message: "无法将用户权限提升到高于自己的级别"
      };
      return;
    }
    
    // 3. 构建更新字段和参数
    const updateFields = [];
    const params = [];
    
    if (username !== undefined) {
      // 检查用户名是否已存在
      const [existingUser] = await db.query(
        "SELECT id FROM user WHERE username = ? AND id != ?",
        [username, id]
      );
      if (existingUser.length > 0) {
        ctx.status = 400;
        ctx.body = {
          code: 400,
          message: "用户名已存在"
        };
        return;
      }
      updateFields.push("username = ?");
      params.push(username);
    }
    
    if (password !== undefined) {
      // 加密新密码
      const salt = bcrypt.genSaltSync(10);
      const hash = bcrypt.hashSync(password, salt);
      updateFields.push("password = ?");
      params.push(hash);
    }
    
    if (nick !== undefined) {
      updateFields.push("nick = ?");
      params.push(nick);
    }
    
    if (type !== undefined) {
      updateFields.push("type = ?");
      params.push(type);
    }
    
    if (email !== undefined) {
      updateFields.push("email = ?");
      params.push(email);
    }
    
    // 如果没有可更新的字段
    if (updateFields.length === 0) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: "没有提供可更新的字段"
      };
      return;
    }
    
    // 4. 执行更新
    const sql = `UPDATE user SET ${updateFields.join(", ")} WHERE id = ?`;
    params.push(id);
    
    const result = await db.query(sql, params);
    
    // 5. 返回成功响应
    ctx.body = {
      code: 200,
      message: "用户信息更新成功",
      data: {
        affectedRows: result.affectedRows
      }
    };
    
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "修改用户信息失败",
      error: error.message
    };
  }
};
/**
 * 用户注册
 * @param {*} ctx
 * * username 账号
 * * password 密码
 * @param {*} next
 * @returns
 */
const register = async (ctx, next) => {
  try {
    const { username, password } = ctx.request.body;

    if (!username || !password) {
      ctx.status = 400;
      ctx.body = { code: 400, message: '用户名和密码不能为空' };
      return;
    }

    try {
      // 检查用户名是否已存在
      const [rows] = await db.query('SELECT * FROM user WHERE username = ?', [username]);
      if (rows.length > 0) {
        ctx.status = 400;
        ctx.body = { code: 400, message: '用户名已存在' };
        return;
      }

      // 加密密码
      const hashedPassword = bcrypt.hashSync(password, 10);
      // 插入新用户
      const [result] = await db.query(
        'INSERT INTO user (username, password, creationTime, lastLoginTime) VALUES (?, ?, NOW(), NOW())',
        [username, hashedPassword]
      );
      // 获取自增ID
      const userId = result.insertId;
      // 设置默认昵称
      await db.query(
        'UPDATE user SET nick = ? WHERE id = ?',
        [`用户${userId}`, userId]
      );

      ctx.status = 201;
      ctx.body = {
        code: 200,
        message: '注册成功',
        data: {
          userId,
          username,
          nick: `用户${userId}`
        }
      };
    } catch (error) {
      console.error(error);
      ctx.status = 500;
      ctx.body = { message: '服务器错误', code: 500 };
    }
  } catch (err) {
    ctx.body = {
      code: 500,
      message: "注册失败",
      data: err,
    };
  }
};
/**
 * 获取用户列表
 * @param { object } ctx
 * * page 页码
 * * pageSize 分页大小
 * @returns {Promise<void>}
 */
const userList = async (ctx) => {
  try {
    // 获取分页参数，默认页码为1，每页显示10条数据
    const page = parseInt(ctx.query.page) || 1; // 当前页，默认为第1页
    const pageSize = parseInt(ctx.query.pageSize) || 10; // 每页显示的条数，默认为10条
    const offset = (page - 1) * pageSize; // 计算偏移量
    // 执行查询，选择需要的字段（排除 password）
    const [results] = await db.query(
      "SELECT id, username, nick, type, headerUrl, creationTime, changeTime, email FROM user LIMIT ? OFFSET ?",
      [pageSize, offset]
    );
    // 如果结果为空，返回空数据提示
    if (results.length === 0) {
      ctx.body = JSON.stringify({
        code: 0,
        message: "No data available", // 无数据时的提示信息
        data: [],
      });
      return;
    }
    // 计算总记录数，以便进行分页信息返回
    const [totalResults] = await db.query(
      "SELECT COUNT(*) AS total FROM user"
    );
    // 返回分页后的数据和总记录数
    ctx.body = JSON.stringify({
      code: 1,
      data: {
        list: results,
        total: totalResults[0].total, // 总记录数
        totalPages: Math.ceil(totalResults[0].total / pageSize), // 总页数
      },
      message: "查询成功",
    });
  } catch (err) {
    // 捕获并处理错误
    ctx.status = 500;
    ctx.body = {
      code: 0,
      message: "Database query failed",
      error: err.message,
    };
  }
};
module.exports = {
  login,
  register,
  addUser,
  updateUser,
  userList,
};
